package protocol.transactions;

import protocol.XoneProtocol;
import protocol.XoneServiceCode;
import protocol.meta.User;

import com.google.gson.JsonElement;
import com.netease.http.THttpRequest;
import com.netease.pkgRelated.ErrorToString;

import db.manager.ManagerAccount;
import db.manager.ManagerAccount.Account;


public class ExternalUserRegTransaction extends EncryptBaseTransaction {
    String mUid;
    String mAccessToken;
    int mType;
    String mNickname;
    String mAvatar;


    public ExternalUserRegTransaction(String uid,String accessToken,int type,String nickname,String avatar) {
        super(TRANSACTION_TYPE_EXTERNAL_USER_REG);
        mUid = uid;
        mAccessToken = accessToken;
        mType = type;
        mNickname = nickname;
        mAvatar = avatar;
    }
    @Override
    protected void onXoneTransactionSuccess(int code, Object obj) {
        User user = null;
        if (obj != null && obj instanceof JsonElement) {
            user = User.fromJson((JsonElement)obj);
        }
        
        if (user != null) {
            Account acc = new Account();
            acc.mUserName = mUid;
            acc.mPassword = mAccessToken;
            acc.mNickName = user.nickname;
            acc.mUserId = user.userId;
            acc.mUserType = user.loginType;
            acc.mIsLastLogin = true;
            acc.mAttr = user.userAttr;
            acc.mAvatar = user.avatar;
            ManagerAccount.getInstance().setLoginAccount(acc);
            notifyMessage(XoneServiceCode.TRANSACTION_SUCCESS, user);
        } else {
            notifyError(XoneServiceCode.ERR_CODE_DATA_PARSE_EXCEPTION,
                    ErrorToString.getString(XoneServiceCode.ERR_CODE_DATA_PARSE_EXCEPTION));
        }
    }
    @Override
    void realOntransact() {
        THttpRequest request = XoneProtocol.getInstance().createExternalUserRegRequest(mUid, mAccessToken,mType,mNickname,mAvatar);
        sendRequest(request);
    }

}
